/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-12-10     Administrator       the first version
 */
#include <rtthread.h>
#include <rtdevice.h>
#include "board.h"
#include "stdint.h"
#define ADC_DEV_NAME "adc0" /* ADC 设备名称 */
#define ADC_DEV_CHANNEL 7 /* ADC 通道 */
#define REFER_VOLTAGE 330 /* 参考电压 3.3V,数据精度乘以 100 保留 2 位小数*/
#define CONVERT_BITS (1 << 10) /* 转换位数为 10 位 */
extern char Function;
char adc_flag=0;
static int adc_vol_sample(void)
{
 rt_adc_device_t adc_dev;
 rt_uint32_t value, vol;
 rt_err_t ret = RT_EOK;
 /* 查找设备 */
 adc_dev = (rt_adc_device_t)rt_device_find(ADC_DEV_NAME);
 if (adc_dev == RT_NULL)
 {
 rt_kprintf("adc sample run failed! can't find %s device!\n", ADC_DEV_NAME);
 return RT_ERROR;
 }
 /* 使能设备 */
 ret = rt_adc_enable(adc_dev, ADC_DEV_CHANNEL);
 /* 读取采样值 */
 value = rt_adc_read(adc_dev, ADC_DEV_CHANNEL);
 rt_kprintf("the value is :%d \n", value);
 /* 转换为对应电压值 */
 vol = value * REFER_VOLTAGE / CONVERT_BITS;
 rt_kprintf("the voltage is :%d.%02d \n", vol / 100, vol % 100);
 /* 关闭通道 */
 ret = rt_adc_disable(adc_dev, ADC_DEV_CHANNEL);
 return value;
}
/* 导出到 msh 命令列表中 */
MSH_CMD_EXPORT(adc_vol_sample, adc voltage convert sample);


#define PWM_DEV_NAME "t5pwm" /* PWM 设备名称 */
#define PWM_DEV_CHANNEL 1 /* PWM 通道 */
struct rt_device_pwm *pwm_dev; /* PWM 设备句柄 */
ALIGN(RT_ALIGN_SIZE)
static uint8_t PWM_Thread_Stack[1024];
static void PWM_Thread_Entry(void *para);
static struct rt_thread pwm_thread;
rt_uint32_t period, pulse;
void Pwm_Init(void){
 period = 1000000; /* 周期 = 1M/period kHz */
 pulse = 0; /* PWM 脉冲宽度值(0 - period) */
 pwm_dev = (struct rt_device_pwm *)rt_device_find(PWM_DEV_NAME);
 RT_ASSERT(pwm_dev != RT_NULL);
 /* 设置 PWM 周期和脉冲宽度 */
 rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, pulse);
 /* 使能设备 */
 rt_pwm_enable(pwm_dev, PWM_DEV_CHANNEL);
}
static void PWM_Thread_Entry(void *para){
 rt_uint32_t value;
 Pwm_Init();
 value= adc_vol_sample();
 rt_pwm_disable(pwm_dev,  PWM_DEV_CHANNEL);
 while(1){
 /*使 RGB 灯红灯闪烁*/
// for (int var = 0; var < period; var += 10000) {
// rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, var);
// rt_thread_mdelay(1000);
     value= adc_vol_sample();
     if(Function==1)
     {
 if(value<500)
     {rt_pwm_enable(pwm_dev, PWM_DEV_CHANNEL);adc_flag=1;}
 else {
    rt_pwm_disable(pwm_dev,  PWM_DEV_CHANNEL);
    adc_flag=2;
}
     }
     else {
         rt_pwm_disable(pwm_dev,  PWM_DEV_CHANNEL);
    }
     rt_thread_mdelay(500);

 }
 }
int Pwm_Thread_Init(void){
 rt_thread_init(&pwm_thread, "pwm_thread", PWM_Thread_Entry, RT_NULL,
 &PWM_Thread_Stack[0], sizeof(PWM_Thread_Stack), 10, 10);
 rt_thread_startup(&pwm_thread);
 return 0;
}
INIT_APP_EXPORT(Pwm_Thread_Init);
